package main

import (
	"fmt"
	"io/ioutil"
	"strconv"
	"time"
)

func main() {
	start := time.Now()
	big := readNumber("./bignumber.txt")
	greatest := findGreatestProduct(big)
	fmt.Println("Greatest product of five consecutive digits is:", greatest)
	stop := time.Now()
	fmt.Println("Execution time: ", stop.Sub(start))

}

func findGreatestProduct(big []int) int {
	greatest := -1
	for i := 0; i < len(big)-4; i++ {
		product := big[i] * big[i+1] * big[i+2] * big[i+3] * big[i+4]
		if product > greatest {
			greatest = product
		}
	}
	return greatest
}

//Reads the file and returns only the actual numbers in a slice of ints
func readNumber(filename string) []int {
	n := 0
	bigNumber := make([]byte, 1000)
	big := make([]int, 1000)
	//Automatically reads the whole file and returns an array of bytes
	buf, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err)
	}
	//We get rid of any byte that is not a number (like '\n')
	//so we keep only the actual numbers. Those are the bytes 48 to 57
	//48 is number 0 and 57 is number 9.
	for k := 0; k < len(buf); k++ {
		if int(buf[k]) >= 48 && int(buf[k]) <= 57 {
			bigNumber[n] = buf[k]
			n++
		}
	}
	//We convert the bytes to ints so we can make calculations
	for i := 0; i < len(bigNumber); i++ {
		big[i], _ = strconv.Atoi(string(bigNumber[i]))
	}
	return big
}
